<template>
  <div class="add-page-dialog">
    <el-dialog
      :visible.sync="pageVisible"
      :before-close="closed"
      :title="dialogTitle"
      destroy-on-close
      width="600px"
    >
      <div class="dialog-container">
        <VFormRender
          v-if="pageVisible"
          ref="render"
          :script="pScript"
          :formJson="json"
        >
        </VFormRender>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as api from "@/api/applicationManage/applicationManage";

export default {
  name: "add-page-dialog",
  props: {
    pageVisible: Boolean,
    field: Object,
  },
  data() {
    return {
      json: {},
      pScript: {
        data: {},
        methods: {},
      },
      operateObj: {
        add: "新增",
        edit: "编辑",
        delete: "删除",
        view: "查看",
      },
    };
  },
  computed: {
    dialogTitle() {
      if (!this.field || !this.field.options || !this.field.options.operateType) {
        return "查看";
      }
      return this.operateObj[this.field.options.operateType];
    },
  },
  watch: {
    pageVisible: {
      handler(val) {
        this.pageVisible = val;
        // 初始化
        if (val) {
          this.updateJson();
        }else{
          this.$emit('pageClosed')
        }
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    close() {
      this.$emit("pageClosed");
    },
    updateJson() {
      if (this.field.options.pageInfo && this.field.options.pageInfo.addPageId) {
        // this.json = JSON.parse(this.field.options.pageInfo.json);
        // this.initScript(this.json.pageScript);
        this.getDetails(this.field.options.pageInfo.addPageId);
      }
    },
    initScript(s) {
      if (s.data) {
        this.pScript.data = JSON.parse(s.data);
      }
      if (s.methods) {
        s.methods.forEach((item) => {
          let obj = {};
          obj[item.funName] = new Function("arguments", item.funBody);
          Object.assign(this.pScript.methods, obj);
        });
      }
    },
    // 根据页面查询页面的json
    getDetails(oid) {
      api.detail({ id: oid }).then((res) => {
        const { json } = res.data.data;
        if (json) {
          this.json = JSON.parse(json);
          this.initScript(this.json.pageScript);
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
.dialog-container {
  width: 100%;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  max-height: 500px;
  overflow-y: scroll;
  padding-left: 100px;

  > div:first-child {
    width: 40%;
  }

  > div:last-child {
    width: 58%;
  }
}
</style>

<style lang="scss">
.select-model-data {
  .el-dialog {
    .el-dialog__body {
      padding: 5px 20px;
    }
  }
}
</style>
